package com.z.system.security;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.z.system.utils.JwtTokenUtil;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * JWT认证过滤器，用于拦截请求并验证JWT令牌
 * 继承OncePerRequestFilter确保每个请求只被过滤一次
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
    private static final String AUTHORIZATION_HEADER = "Authorization";

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 过滤器核心方法，处理每个请求
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response,
            FilterChain chain)
            throws ServletException, IOException {

        // 不处理OPTIONS请求，允许跨域预检请求通过
        if (!request.getMethod().equals("OPTIONS")) {
            // 获取请求头中的Authorization信息
            final String jwtToken = request.getHeader(AUTHORIZATION_HEADER);
            String username = null;
            try {
                // 从令牌中获取用户名
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (Exception e) {
                // 令牌解析失败，记录日志但不中断过滤链
                // 对于permitAll的路径，Spring Security会在后续处理中允许访问
                logger.error("Unable to get JWT Token or token has expired");
            }
            // 验证令牌并设置认证信息
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = null;
                // 验证令牌是否有效
                if (jwtTokenUtil.validateToken(jwtToken, username)) {
                    // 加载用户信息
                    try {
                        userDetails = this.userDetailsService.loadUserByUsername(username);
                    } catch (UsernameNotFoundException e) {
                        // 用户不存在，记录日志
                        logger.error("User not found: " + username);
                        // 继续过滤链，允许后续处理（如403错误）
                        chain.doFilter(request, response);
                        return;
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    // 创建认证令牌
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());

                    // 设置认证详情
                    usernamePasswordAuthenticationToken
                            .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    // 将认证信息设置到SecurityContext中
                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                }
            }
        }

        // 继续过滤链
        chain.doFilter(request, response);
    }
}